package by.dezhits.makeanote.content;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import by.dezhits.makeanote.R;
import by.dezhits.makeanote.content.contract.FoldersContract;
import by.dezhits.makeanote.db.DBHelper;

public class FoldersProvider extends ContentProvider {

	private DBHelper dbHelper;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		dbHelper.deleteFolders(selection);
		getContext().getContentResolver().notifyChange(
				FoldersContract.FoldersColumns.CONTENT_URI, null);
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO if id != null {dbHelper.setPasswordForFolder}
		Integer id = values.getAsInteger(getContext().getString(R.string.id));
		long insertId;
		if (id == null) {
			insertId = dbHelper.addFolder(
					values.getAsString(getContext().getString(R.string.name)),
					values.getAsString(getContext().getString(R.string.pass)));
		} else {
			insertId = dbHelper.setPasswordForFolder(id,
					values.getAsString(getContext().getString(R.string.name)),
					values.getAsString(getContext().getString(R.string.pass)));
		}
		if (insertId != -1) {
			getContext().getContentResolver().notifyChange(
					FoldersContract.FoldersColumns.CONTENT_URI, null);
		}
		return ContentUris.withAppendedId(
				FoldersContract.FoldersColumns.CONTENT_URI, insertId);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		dbHelper = new DBHelper(getContext(), null);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor cursor = dbHelper
				.getFolders(selection, selectionArgs, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}
